<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Present } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 기본 데이터
const loading = ref(true)
const room = ref<any>(null)
const messages = ref<any[]>([])
const inputText = ref('')
const messagesContainer = ref<HTMLElement>()
const imageInput = ref<HTMLInputElement | null>(null)
const uploadingImage = ref(false)

// 선물 관련
const showGiftPanel = ref(false)
const gifts = ref<any[]>([])
const selectedGift = ref<any>(null)
const giftQuantity = ref(1)
const chatRoomUsers = ref<any[]>([])
const selectedReceiver = ref<any>(null)
const sendingGift = ref(false)

// SSE 연결
let es: EventSource | null = null

// 계산된 속성
const isAdmin = computed(() => authStore.isAdmin)
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || ''

onMounted(async () => {
  await fetchRoom()
  await fetchMessages()
  await fetchGifts()
  connectSSE()
  scrollToBottom()
})

onUnmounted(() => {
  if (es) {
    es.close()
    es = null
  }
})

// 채팅방 정보 가져오기
async function fetchRoom() {
  try {
    const res = await request.get(`/api/chat/rooms/${route.params.id}`)
    room.value = res.data
  } catch (error) {
    ElMessage.error('채팅방 정보 가져오기 실패')
    router.back()
  } finally {
    loading.value = false
  }
}

// 이전 메시지 가져오기
async function fetchMessages() {
  try {
    const res = await request.get(`/api/chat/rooms/${route.params.id}/history?limit=50`)
    messages.value = res.data.messages || []
    scrollToBottom()
  } catch (error) {
    console.error('이전 메시지 가져오기 실패:', error)
  }
}

// 선물 목록 가져오기
async function fetchGifts() {
  try {
    const res = await request.get('/api/chat/gifts')
    gifts.value = res.data || []
  } catch (error) {
    console.error('선물 목록 가져오기 실패:', error)
  }
}

// 채팅방 사용자 목록 가져오기
async function fetchChatRoomUsers() {
  if (!route.params.id) return
  try {
    const res = await request.get(`/api/chat/rooms/${route.params.id}/users?limit=50`)
    chatRoomUsers.value = res.data.users || []
  } catch (error) {
    console.error('채팅방 사용자 가져오기 실패:', error)
  }
}

// SSE 연결
function connectSSE() {
  const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || ''
  const sseUrl = `${API_BASE_URL}/api/chat/rooms/${route.params.id}/stream`
  console.log('连接SSE:', sseUrl)

  es = new EventSource(sseUrl)

  es.addEventListener('open', () => {
    console.log('SSE连接已建立')
  })

  es.addEventListener('error', (error) => {
    console.error('SSE连接错误:', error)
  })

  es.addEventListener('message', (ev) => {
    console.log('收到消息事件:', ev.data)
    const data = JSON.parse(ev.data)
    pushMessage(data)
  })

  es.addEventListener('gift', (ev) => {
    console.log('管理员端收到礼物事件:', ev.data)
    const data = JSON.parse(ev.data)
    pushMessage(data)
    // 管理员端也可以看到礼物特效
    try {
      const preset = data.giftEffectPreset || 'burst'
      import('@/utils/useGiftEffects').then((m) =>
        m.useGiftEffects().trigger(preset, Number(data.quantity || 1)),
      )
    } catch (error) {
      console.error('管理员端礼物特效失败:', error)
    }
  })

  es.addEventListener('system', (ev) => {
    console.log('收到系统事件:', ev.data)
    const data = JSON.parse(ev.data)
    pushMessage(data)
  })
}

// 添加消息到列表
function pushMessage(data: any) {
  messages.value.push({
    id: data.id || Date.now(),
    content: data.content,
    messageType: data.messageType || 'text',
    imageUrl: data.imageUrl,
    username: data.username,
    avatar: data.avatar,
    timestamp: new Date(data.timestamp),
    senderUserId: data.senderUserId,
    isSystem: data.isSystem,
    isGift: data.isGift
  })

  // 保持消息列表不超过100条
  if (messages.value.length > 100) {
    messages.value = messages.value.slice(-100)
  }

  scrollToBottom()
}

// 发送消息
async function sendMessage() {
  const text = inputText.value.trim()
  if (!text) return

  console.log('发送消息:', text)
  try {
    const response = await request.post(`/api/admin/chat-rooms/${route.params.id}/messages`, {
      content: text,
      isSystem: false
    })
    console.log('消息发送响应:', response)
    inputText.value = ''
    ElMessage.success('消息发送成功')
  } catch (error: any) {
    console.error('发送消息失败:', error)
    ElMessage.error(error.response?.data?.error || '发送消息失败')
  }
}

// 选择图片
function selectImage() {
  imageInput.value?.click()
}

// 处理图片选择
async function handleImageSelect(event: Event) {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }

  // 检查文件大小 (10MB)
  if (file.size > 10 * 1024 * 1024) {
    ElMessage.error('图片文件不能超过10MB')
    return
  }

  uploadingImage.value = true
  try {
    // 上传图片
    const formData = new FormData()
    formData.append('image', file)

    const uploadResponse = await request.post('/api/admin/uploads/chat-image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    console.log('管理员端图片上传成功:', uploadResponse)

    // 发送图片消息
    const messageResponse = await request.post(`/api/admin/chat-rooms/${route.params.id}/messages`, {
      messageType: 'image',
      imageUrl: uploadResponse.data.imageUrl,
      isSystem: false
    })

    console.log('管理员端图片消息发送成功:', messageResponse)
    ElMessage.success('图片发送成功')
  } catch (error: any) {
    console.error('管理员端发送图片失败:', error)
    ElMessage.error(error.response?.data?.error || '发送图片失败，请重试')
  } finally {
    uploadingImage.value = false
    // 清空文件选择
    if (target) target.value = ''
  }
}

// 预览图片
function previewImage(imageUrl: string) {
  window.open(imageUrl, '_blank')
}

// 打开礼物面板
async function openGiftPanel() {
  showGiftPanel.value = true
  await fetchChatRoomUsers()
}

// 选择礼物
function selectGift(gift: any) {
  selectedGift.value = gift
}

// 选择收礼人
function selectReceiver(user: any) {
  selectedReceiver.value = user
}

// 发送礼物
async function sendGift() {
  if (!selectedGift.value || !selectedReceiver.value) {
    ElMessage.warning('请选择礼物和收礼人')
    return
  }

  console.log('管理员端发送礼物:', {
    giftId: selectedGift.value.id,
    giftName: selectedGift.value.name,
    quantity: giftQuantity.value,
    receiverUserId: selectedReceiver.value.id,
    receiverName: selectedReceiver.value.nickname || selectedReceiver.value.name
  })

  sendingGift.value = true
  try {
    const response = await request.post(`/api/chat/rooms/${route.params.id}/gifts/send`, {
      giftId: selectedGift.value.id,
      quantity: giftQuantity.value,
      receiverUserId: selectedReceiver.value.id
    })

    console.log('管理员端礼物发送响应:', response)
    ElMessage.success('선물 발송 성공')
    showGiftPanel.value = false
    selectedGift.value = null
    selectedReceiver.value = null
    giftQuantity.value = 1
  } catch (error: any) {
    console.error('管理员端发送礼物失败:', error)
    ElMessage.error(error.response?.data?.error || '发送礼物失败')
  } finally {
    sendingGift.value = false
  }
}

// 滚动到底部
function scrollToBottom() {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 시간 포맷
function formatTime(date: Date | string) {
  const d = typeof date === 'string' ? new Date(date) : date
  return d.toLocaleTimeString('ko-KR', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 채팅방 관리로 돌아가기
function goBack() {
  router.push('/chat-rooms')
}
</script>

<template>
  <div class="admin-chat-room" v-if="!loading && room">
    <!-- 헤더 -->
    <div class="header">
      <el-button :icon="ArrowLeft" @click="goBack">채팅방 관리로 돌아가기</el-button>
      <h2>{{ room.title || '채팅방' }}</h2>
      <div class="header-actions">
        <el-button type="primary" :icon="Present" @click="openGiftPanel">선물 발송</el-button>
      </div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-container">
      <!-- 消息列表 -->
      <div ref="messagesContainer" class="messages">
        <div
          v-for="message in messages"
          :key="message.id"
          class="message"
          :class="{
            'system-message': message.isSystem,
            'gift-message': message.isGift,
            'admin-message': String(message.senderUserId) === String(authStore.user?.id)
          }"
        >
          <img :src="message.avatar" :alt="message.username" class="message-avatar" />
          <div class="message-content">
            <div class="message-header">
              <span class="username">{{ message.username }}</span>
              <span class="timestamp">{{ formatTime(message.timestamp) }}</span>
            </div>
            <div class="message-text">
              <template v-if="message.messageType === 'image' && message.imageUrl">
                <img
                  :src="`${API_BASE_URL}${message.imageUrl}`"
                  :alt="message.content"
                  class="message-image"
                  @click="previewImage(`${API_BASE_URL}${message.imageUrl}`)"
                />
                <div class="image-caption">{{ message.content }}</div>
              </template>
              <template v-else>
                {{ message.content }}
              </template>
            </div>
          </div>
        </div>
      </div>

      <!-- 입력 영역 -->
      <div class="input-area">
        <input
          v-model="inputText"
          placeholder="메시지 입력..."
          @keyup.enter="sendMessage"
          class="message-input"
        />
        <input
          ref="imageInput"
          type="file"
          accept="image/*"
          style="display: none"
          @change="handleImageSelect"
        />
        <button class="image-btn" @click="selectImage" title="이미지 발송">📷</button>
        <button class="send-btn" @click="sendMessage" :disabled="!inputText.trim()">
          발송
        </button>
      </div>
    </div>

    <!-- 선물 발송 패널 -->
    <el-drawer v-model="showGiftPanel" title="선물 발송" size="400px">
      <div class="gift-panel">
        <!-- 선물 선택 -->
        <div class="section">
          <h4>선물 선택</h4>
          <div class="gift-grid">
            <div
              v-for="gift in gifts"
              :key="gift.id"
              class="gift-item"
              :class="{ selected: selectedGift?.id === gift.id }"
              @click="selectGift(gift)"
            >
              <div class="gift-icon-container">
                <img
                  v-if="gift.iconUrl"
                  :src="`${API_BASE_URL}${gift.iconUrl}`"
                  :alt="gift.name"
                  class="gift-icon"
                />
                <div v-else class="gift-icon-placeholder">🎁</div>
              </div>
              <div class="gift-name">{{ gift.name }}</div>
              <div class="gift-price">{{ gift.pricePoints }} 포인트</div>
            </div>
          </div>
        </div>

        <!-- 수신자 선택 -->
        <div class="section" v-if="selectedGift">
          <h4>수신자 선택</h4>
          <div class="user-list">
            <div
              v-for="user in chatRoomUsers"
              :key="user.id"
              class="user-item"
              :class="{ selected: selectedReceiver?.id === user.id }"
              @click="selectReceiver(user)"
            >
              <img :src="user.avatarUrl || 'https://picsum.photos/32'" :alt="user.nickname || user.name" class="user-avatar" />
              <div class="user-info">
                <div class="user-name">{{ user.nickname || user.name }}</div>
                <div class="user-preview">{{ user.lastMessagePreview }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 수량 선택 -->
        <div class="section" v-if="selectedGift && selectedReceiver">
          <h4>수량</h4>
          <el-input-number v-model="giftQuantity" :min="1" :max="99" />
          <div class="total-cost">
            총계: {{ (selectedGift.pricePoints * giftQuantity) }} 포인트
          </div>
        </div>

        <!-- 발송 버튼 -->
        <div class="section" v-if="selectedGift && selectedReceiver">
          <el-button
            type="primary"
            size="large"
            :loading="sendingGift"
            @click="sendGift"
            style="width: 100%"
          >
            선물 발송
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>

  <div v-else-if="loading" class="loading">
    <el-loading-directive />
    <p>로딩 중...</p>
  </div>
</template>

<style scoped>
/* 整体布局 */
.admin-chat-room {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--color-bg);
  color: var(--color-text);
  overflow: hidden;
}

/* 聊天室头部 */
.header {
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  gap: var(--space-3);
  padding: var(--space-4);
  border-bottom: 1px solid var(--color-border);
  background: var(--color-bg);
  flex-shrink: 0;
  z-index: 30;
  box-shadow: var(--shadow-sm);
}

.header h2 {
  flex: 1;
  margin: 0;
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--color-text);
}

.header-actions {
  display: flex;
  gap: var(--space-3);
}

/* 自定义返回按钮样式，匹配用户端 */
.header :deep(.el-button) {
  background: var(--color-surface);
  color: var(--color-text);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  font-weight: 500;
  transition: all 0.2s;
}

.header :deep(.el-button:hover) {
  background: var(--color-primary);
  color: white;
  border-color: var(--color-primary);
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
}

.header :deep(.el-button--primary) {
  background: var(--color-primary);
  border-color: var(--color-primary);
  box-shadow: var(--shadow-md);
}

.header :deep(.el-button--primary:hover) {
  background: var(--color-primary-hover, #ff5722);
  transform: translateY(-1px);
  box-shadow: var(--shadow-lg);
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

/* 消息区域（仅此处滚动） */
.messages {
  flex: 1;
  min-height: 0; /* 允许在flex容器中收缩以启用滚动 */
  overflow-y: auto;
  overflow-x: hidden;
  padding: var(--space-4);
  display: flex;
  flex-direction: column;
  gap: var(--space-3);
  scroll-behavior: smooth;
  background: var(--color-surface, #f8fafc);
}

/* 自定义滚动条 */
.messages::-webkit-scrollbar {
  width: 6px;
}

.messages::-webkit-scrollbar-track {
  background: var(--color-surface, #f8fafc);
  border-radius: 3px;
}

.messages::-webkit-scrollbar-thumb {
  background: var(--color-border, #e2e8f0);
  border-radius: 3px;
}

.messages::-webkit-scrollbar-thumb:hover {
  background: var(--color-text-muted, #94a3b8);
}

/* 消息样式 */
.message {
  display: flex;
  align-items: flex-start;
  gap: var(--space-2, 8px);
}

.message.admin-message {
  flex-direction: row-reverse;
}

.message.system-message {
  justify-content: center;
}

.message.system-message .message-content {
  background: var(--color-warning, #f59e0b);
  color: var(--color-text);
  border-radius: 9999px;
  padding: 8px 16px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
}

.message.gift-message .message-text {
  background: linear-gradient(135deg, var(--color-accent, #ffd93d), #fff9e6);
  color: var(--color-text);
  font-weight: 600;
  box-shadow: var(--shadow-md);
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
  flex-shrink: 0;
  border: 2px solid var(--color-border, #e2e8f0);
  box-shadow: var(--shadow-sm);
}

.message-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.message-header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: var(--space-2, 8px);
  color: var(--color-text-muted, #94a3b8);
  font-size: 0.75rem;
  margin-bottom: 2px;
}

.username {
  font-weight: 600;
  color: var(--color-text);
}

.timestamp {
  font-size: 11px;
  color: var(--color-text-muted, #94a3b8);
}

.message-text {
  max-width: min(80%, 720px);
  width: fit-content;
  background: white;
  color: var(--color-text);
  border: 1px solid var(--color-border, #e2e8f0);
  border-radius: var(--radius-lg, 14px);
  padding: 12px 16px;
  box-shadow: var(--shadow-sm);
  word-wrap: break-word;
  position: relative;
  line-height: 1.4;
}

.message-text::before {
  content: '';
  position: absolute;
  top: 8px;
  left: -6px;
  width: 0;
  height: 0;
  border-top: 6px solid transparent;
  border-bottom: 6px solid transparent;
  border-right: 6px solid white;
}

.admin-message .message-content {
  align-items: flex-end;
}

.admin-message .message-header {
  justify-content: flex-end;
  gap: 6px;
  text-align: right;
}

.admin-message .message-header .username {
  order: 2;
}

.admin-message .message-header .timestamp {
  order: 1;
}

.admin-message .message-text {
  margin-left: auto;
  background: var(--color-primary, #ff6b35);
  color: white;
  border-color: var(--color-primary, #ff6b35);
}

.admin-message .message-text::before {
  left: auto;
  right: -6px;
  border-right: none;
  border-left: 6px solid var(--color-primary, #ff6b35);
}

/* 底部工具栏（作为页面内容的一部分） */
.input-area {
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  gap: var(--space-3, 12px);
  padding: var(--space-4, 16px);
  background: white;
  border-top: 1px solid var(--color-border, #e2e8f0);
  box-shadow: var(--shadow-lg);
  z-index: 20;
}

.message-input {
  flex: 1;
  padding: 12px 16px;
  background: var(--color-surface, #f8fafc);
  border: 1px solid var(--color-border, #e2e8f0);
  border-radius: var(--radius-full, 9999px);
  color: var(--color-text);
  font-size: 14px;
  transition: all 0.2s;
}

.message-input:focus {
  outline: none;
  border-color: var(--color-primary, #ff6b35);
  box-shadow: 0 0 0 3px rgba(255, 107, 53, 0.2);
  background: white;
}

.message-input::placeholder {
  color: var(--color-text-muted, #94a3b8);
}

.send-btn {
  background: var(--color-primary, #ff6b35);
  color: white;
  border: none;
  border-radius: var(--radius-full, 9999px);
  padding: 12px 24px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.2s;
  box-shadow: var(--shadow-md);
  white-space: nowrap;
}

.send-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.send-btn:hover:not(:disabled) {
  background: var(--color-primary-hover, #ff5722);
  transform: translateY(-1px);
  box-shadow: var(--shadow-lg);
}

.send-btn:active {
  transform: translateY(0);
}

/* 加载状态 */
.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
  font-size: 16px;
  color: var(--color-text-muted, #94a3b8);
}

/* 礼物面板样式 */
.gift-panel {
  padding: var(--space-4, 16px);
}

.section {
  margin-bottom: var(--space-6, 24px);
}

.section h4 {
  margin: 0 0 var(--space-3, 12px) 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--color-text);
}

.gift-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  gap: var(--space-3, 12px);
}

.gift-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: var(--space-3, 12px) var(--space-2, 8px);
  border: 2px solid var(--color-border, #e2e8f0);
  border-radius: var(--radius-md, 10px);
  cursor: pointer;
  transition: all 0.2s;
  background: white;
}

.gift-item:hover {
  border-color: var(--color-primary, #ff6b35);
  background: var(--color-primary-light, #fff3f0);
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
}

.gift-item.selected {
  border-color: var(--color-primary, #ff6b35);
  background: var(--color-primary-light, #fff3f0);
  box-shadow: var(--shadow-md);
}

.gift-icon-container {
  width: 32px;
  height: 32px;
  margin-bottom: var(--space-1, 4px);
  display: flex;
  align-items: center;
  justify-content: center;
}

.gift-icon {
  width: 32px;
  height: 32px;
  object-fit: cover;
  border-radius: var(--radius-sm, 6px);
  border: 1px solid var(--color-border, #e2e8f0);
}

.gift-icon-placeholder {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--color-surface, #f8fafc);
  border: 1px solid var(--color-border, #e2e8f0);
  border-radius: var(--radius-sm, 6px);
  font-size: 16px;
}

.gift-name {
  font-size: 12px;
  font-weight: 500;
  text-align: center;
  margin-bottom: 2px;
  color: var(--color-text);
}

.gift-price {
  font-size: 11px;
  color: var(--color-warning, #f59e0b);
  font-weight: 500;
}

.user-list {
  max-height: 200px;
  overflow-y: auto;
  border-radius: var(--radius-md, 10px);
}

.user-item {
  display: flex;
  align-items: center;
  gap: var(--space-3, 12px);
  padding: var(--space-2, 8px) var(--space-3, 12px);
  border-radius: var(--radius-sm, 6px);
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: var(--space-1, 4px);
}

.user-item:hover {
  background: var(--color-surface, #f8fafc);
  transform: translateX(4px);
}

.user-item.selected {
  background: var(--color-primary-light, #fff3f0);
  border: 1px solid var(--color-primary, #ff6b35);
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  flex-shrink: 0;
  border: 2px solid var(--color-border, #e2e8f0);
}

.user-info {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--color-text);
}

.user-preview {
  font-size: 12px;
  color: var(--color-text-muted, #94a3b8);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.total-cost {
  margin-top: var(--space-2, 8px);
  font-size: 14px;
  font-weight: 600;
  color: var(--color-warning, #f59e0b);
  text-align: center;
  padding: var(--space-2, 8px);
  background: #fff9e6;
  border-radius: var(--radius-md, 10px);
}

/* 图片按钮样式 */
.image-btn {
  background: var(--color-surface, #f8fafc);
  color: var(--color-text);
  border: 1px solid var(--color-border, #e2e8f0);
  border-radius: var(--radius-full, 9999px);
  padding: 12px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 44px;
  height: 44px;
}

.image-btn:hover {
  background: var(--color-primary, #ff6b35);
  color: white;
  border-color: var(--color-primary, #ff6b35);
  transform: translateY(-1px);
}

/* 图片消息样式 */
.message-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: var(--radius-md, 10px);
  cursor: pointer;
  transition: all 0.2s;
  display: block;
  margin-bottom: var(--space-2, 8px);
}

.message-image:hover {
  transform: scale(1.02);
  box-shadow: var(--shadow-lg);
}

.image-caption {
  font-size: 12px;
  color: var(--color-text-muted, #94a3b8);
  font-style: italic;
}
</style>
